 package com.aiYouPms.admin.controller;

import com.aiYouPms.admin.bo.AdminUserDetails;
import com.aiYouPms.admin.util.JwtTokenUtil;
import com.aiYouPms.admin.dto.LoginParams;
import com.aiYouPms.common.api.HttpResult;
import com.aiYouPms.common.model.AdminUser;
import com.aiYouPms.common.service.AdminUserService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Controller
@ResponseBody
@RequestMapping("/admin")
public class AdminController {

    private final AdminUserService adminUserService;

    private final AuthenticationManager authenticationManager;

    private final JwtTokenUtil jwtTokenUtil;

    public AdminController(AdminUserService adminUserService,
                           AuthenticationManager authenticationManager,
                           JwtTokenUtil jwtTokenUtil) {

        this.adminUserService = adminUserService;
        this.authenticationManager = authenticationManager;
        this.jwtTokenUtil = jwtTokenUtil;
    }

    @PostMapping("/login")
    public HttpResult<Map<String, String>> login(@Validated @RequestBody LoginParams loginParams) {
        if (loginParams == null || loginParams.getUsername() == null || loginParams.getPassword() == null) {
            return HttpResult.error("用户名和密码不能为空");
        }

        try {
            // 尝试使用提供的用户名和密码进行认证
            authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginParams.getUsername(), loginParams.getPassword())
            );
        } catch (BadCredentialsException e) {
            return HttpResult.error("用户名或密码错误");
        }

        // 认证成功，加载用户详细信息
        AdminUser adminUser = adminUserService.loadUserByUsername(loginParams.getUsername());

        // 检查用户是否存在
        if (adminUser == null) {
            return HttpResult.error("用户不存在");
        }

        UserDetails userDetails = new AdminUserDetails(adminUser);

        // 生成 JWT 令牌
        final String jwt = jwtTokenUtil.generateToken(userDetails.getUsername());

        // 返回包含 JWT 的响应
        Map<String, String> response = new HashMap<>();
        response.put("token", jwt);
        return HttpResult.success("登录成功", response);
    }
}